import {
  getWebapiPage,
  createWebapi,
  updateWebapiById,
  delWebapiById,
  testingByid,
  updateStatusByid,
  testingLogsById,
  getLogsById
} from "@/api/robotTaskWebapi";

import { getAllBrandsPage } from "@/api/brand";
import { getProjLists } from "@/api/order";
import { getDataByCode, checkUserToken } from "@/api/user";
import { curentTime, curentDate } from "@/filters/index";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; //  分页器
import pdf from "@/components/pdf"; //  pdf预览
import checkPermission from "@/utils/permission"; // 权限判断函数
import { paramsDataDeal } from "@/utils/index";
// 导入模块
import vueJsonEditor from "vue-json-editor";
export default {
  name: "robotTaskWebapi",
  components: { Pagination, vueJsonEditor, pdf },
  directives: { waves },
  filters: {
    formate(date) {
      return curentTime(date);
    },
  },
  data() {
    return {
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      statusArr: [
        { name: "未开始", code: "NOT_START" },
        { name: "进行中", code: "START" },
        { name: "已结束", code: "END" },
      ],
      timeTypeArr: [
        {
          name: "通知截止日期",
          code: "webapi_endtime"
        },
        {
          name: "创建时间",
          code: "created_at"
        },
        {
          name: "修改时间",
          code: "updated_at"
        },
        {
          name: "最新测试时间",
          code: "testing_time"
        }
      ],
      testingTypeArr: [
        {
          name: "正常",
          code: 1
        },
        {
          name: "异常",
          code: 0
        }
      ],
      testingArr: [
        { name: "1小时", code: 1 },
        { name: "2小时", code: 2 },
        { name: "6小时", code: 6 },
        { name: "12小时", code: 12 },
        { name: "24小时", code: 24 },
      ],
      methodTypeLists: ["GET", "POST"],
      // 项目数据
      pageList: [],
      // 项目总数
      total: 0,
      // 加载
      listLoading: true,
      // 查询参数
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        searchKey: null,
        webapiStatus: null,
        testingStatus: null,
        filterDateType: null,
        filterDate: null,
      },
      searchKey: "",
      // 表单控制
      dialogFormVisible: false,
      // 表单标题
      title: "",
      // 表单参数
      form: {
        id: "",
        webapiClass: "",
        webapiName: "",
        webapiContent: "",
        webapiType: null,
        webapiEndtime: null,
        webapiUserid: null,
        webapiConfig: null,
        brandId: null,
        brandName: "",
        projectId: null,
        projectName: "",
        testingInterval: 1,
        sendSuccessMsg: true,
        webapiMethod: "",
        webapiDomain: "",
        webapiPath: "",
        webapiCheck: "",
        webapiData: null,
        webapiUseridArr: [],
      },
      webapiDataObj: null,
      orderIDs: "",
      // 表单检验
      rules: {
        webapiName: [
          { required: true, message: "请输入通知名称", trigger: "blur" },
        ],
        webapiType: [
          { required: true, message: "请选择通知类型", trigger: "change" },
        ],
        webapiEndtime: [
          { required: true, message: "请选择通知时间", trigger: "change" },
        ],
        webapiUseridArr: [
          { required: true, message: "请选择负责人", trigger: "change" },
        ],
        webapiConfig: [
          { required: true, message: "请输入通知配置内容", trigger: "blur" },
        ],
        webapiClass: [
          { required: true, message: "选择类型", trigger: "blur" },
        ],
        webapiDomain: [
          { required: true, message: "请输入正确的域名", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
              if (!reg.test(value)) {
                callback(new Error('请输入正确的域名'));
              } else {
                callback();
              }
            }, trigger: 'blur'
          }
        ],
        webapiPath: [
          { required: true, message: "请填写API路径", trigger: "blur" },
        ],
        webapiData: [
          { required: true, message: "请填写API参数配置", trigger: "blur" },
        ],
        webapiMethod: [
          { required: true, message: "请选择请求方式", trigger: "blur" },
        ],
        testingInterval: [
          { required: true, message: "请选择自动测试间隔", trigger: "change" },
        ],
      },
      webapiClassArr: [{ name: "网站监测", code: "web" }, { name: "API监测", code: "api" }],
      // 通知方式
      robotAlarmTypeLists: [],
      userLists: [],
      currTagUserId: "", //  当前用户的unionId
      // json是否验证通过
      hasJsonFlag: true,
      brandsLists: [], //	品牌列表
      projectLists: [], //	项目列表
      testingFormVisible: false,
      testingForm: {

      },
      tagWebapi: null,
      isDetails: false,
      pdfurl: "https://morefun-active.oss-cn-beijing.aliyuncs.com/morefun_oa/%E7%BD%91%E7%AB%99%26API%E5%91%8A%E8%AD%A6.pdf",
      pdfhref: "https://morefun.yuque.com/kd0dsy/pyy99r/cd6zpplmy9hx32an",
      webapiLogsData: [],
      webapiLogsVisible: false
    };
  },
  async created() {
    //	获取项目列表
    this.getProjLists();
    //	获取品牌列表
    this.getAllBrandsPage();
    //	任务分页查询
    await this.getPageList();

    // 获取配置数据
    getDataByCode({ code: "RobotAlarm,OnJobUser,HttpData" }).then((res) => {
      this.robotAlarmTypeLists = res.data.RobotAlarm || null;
      this.userLists = res.data.OnJobUser || null;
      this.webapiDataObj = res.data.HttpData || null;
    });
  },
  methods: {
    checkPermission,
    //  手动测试
    async testingByid(row) {
      const res = await testingByid({ id: row.id });
      this.testingFormVisible = true;
      this.getPageList();
      const { isSuccess, logRes } = res.data.httpRes;
      const { success, data } = res.data.alarmRes;
      this.testingForm.api_status = isSuccess || false;
      this.testingForm.api_res = JSON.stringify(logRes);

      this.testingForm.dd_status = success || false;
      this.testingForm.dd_res = success ? JSON.stringify(data) : JSON.stringify(res.data.alarmRes);
    },
    //	获取项目列表
    async getProjLists() {
      const projects = await getProjLists();
      if (projects.success) {
        this.projectLists = projects.data;
      }
    },
    //	获取品牌信息
    async getAllBrandsPage() {
      const brands = await getAllBrandsPage();
      if (brands.success) {
        this.brandsLists = brands.data;
      }
    },
    //	品牌选中
    brandIdSel(e) {
      const _item = this.brandsLists.filter((item) => {
        return item.brand_name == e;
      });
      this.form.brandName = e || null;
      this.form.brandId = e && _item[0] ? _item[0].id : null;
      if (!_item[0] || !_item[0].alarm_config) return console.log("######  当前品牌数据暂未配置钉钉通知信息  ######")
      if (this.form.webapiConfig) {
        this.$confirm('通知配置已经有内容，是否覆盖?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.webapiType = 'GroupRobot';
          this.form.webapiConfig = JSON.parse(_item[0].alarm_config);
          //  解决this.$confirm出现时 select选择展开问题
          this.$refs.selectBrandName.blur();
        }).catch(() => {
          //  解决this.$confirm出现时 select选择展开问题
          this.$refs.selectBrandName.blur();
        });
      } else {
        this.form.webapiConfig = JSON.parse(_item[0].alarm_config);
      }
      
    },
    //	项目选中
    projectIdSel(e) {
      const _item = this.projectLists.filter((item) => {
        return item.project_name == e;
      });
      this.form.projectName = e || null;
      this.form.projectId = e && _item[0] ? _item[0].id : null;
    },
    // json编辑器回调方法
    onJsonSave(value) {
      this.form.webapiConfig = value;
      this.hasJsonFlag = true;
    },
    // json编辑器回调方法
    onWebapiJsonSave(value) {
      this.form.webapiData = value;
      this.hasJsonFlag = true;
    },
    onError(value) {
      this.hasJsonFlag = false;
    },
    // 通知类型选择回调方法
    async webapiTypeSel(e) {
      let res = await getDataByCode({ code: e });

      if (this.form.webapiConfig) {
        this.$confirm('通知配置已经有内容，是否覆盖?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.webapiConfig = res.success ? res.data[e] : {};
          //  解决this.$confirm出现时 select选择展开问题
          this.$refs.selectWebapiType.blur();
        }).catch(() => {
          //  解决this.$confirm出现时 select选择展开问题
          this.$refs.selectWebapiType.blur();
        });
      } else {
        this.form.webapiConfig = res.success ? res.data[e] : {};
      }
    },
    //  类型选择
    webapiClassSel(e) {
      if (this.tagWebapi) {
        this.form.testingInterval = this.tagWebapi.testing_interval || 1;
        this.form.sendSuccessMsg = this.tagWebapi.send_success_msg ? true : false;
        this.form.webapiMethod = this.tagWebapi.webapi_method || null;
        this.form.webapiDomain = this.tagWebapi.webapi_domain || null;
        this.form.webapiPath = this.tagWebapi.webapi_path || null;
        this.form.webapiCheck = this.tagWebapi.testing_iinterval || null;
      } else {
        this.form.testingInterval = 1;
        this.form.sendSuccessMsg = true;
        this.form.webapiMethod = null;
        this.form.webapiDomain = null;
        this.form.webapiPath = null;
        this.form.webapiCheck = null;
      }
      this.form.webapiMethod = e == "web" ? "GET" : "";
    },
    // 按需查询
    async handleFilter() {
      this.listQuery.pageNum = 1;
      await this.getPageList();
    },

    // 查询项目数据
    async getPageList() {
      try {
        //	处理请求参数
        const _obj = JSON.parse(JSON.stringify(this.listQuery));

        if (!_obj.filterDateType || !_obj.filterDate) {
          delete _obj.filterDateType;
          delete _obj.filterDate;
        }

        const _params = await paramsDataDeal(_obj);

        const res = await getWebapiPage(_params);
        this.currTagUserId = res.data.id;
        this.total = res.data.total;
        this.pageList = res.data.lists;
        this.listLoading = false;
      } catch (error) {
        console.log("#####  getPageList-error", error);
      }
    },

    // 提交表单信息
    async submitForm(formName) {
      // 负责人
      if (!this.form.webapiUseridArr || !this.form.webapiUseridArr.length) {
        return this.$message({
          message: "负责人列表不能为空！",
          type: "error",
        });
      }

      //  筛选需要通知的用户数据
      let webapiUserid = [];
      for (let i = 0; i < this.userLists.length; i++) {
        const el = this.userLists[i];
        for (let k = 0; k < this.form.webapiUseridArr.length; k++) {
          const _unionid = this.form.webapiUseridArr[k];
          if (el.unionid == _unionid) {
            webapiUserid.push({
              userid: el.userid,
              unionid: el.unionid,
              name: el.name,
            });
          }
        }
      }

      if (typeof this.form.webapiData != "object") return this.$message({
        message: "API参数配置必须为对象，并包含 headers,body,params",
        type: "error",
      });

      if (!this.form.webapiData.headers) return this.$message({
        message: "API参数配置headers不能为空",
        type: "error",
      });
      if (!this.form.webapiData.body) return this.$message({
        message: "API参数配置body不能为空",
        type: "error",
      });
      if (!this.form.webapiData.params) return this.$message({
        message: "API参数配置params不能为空",
        type: "error",
      });

      this.form.webapiUserid = webapiUserid;
      // 表单验证
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (typeof this.form.webapiEndtime == "object") {
            this.form.webapiEndtime = curentDate(this.form.webapiEndtime);
          }
          // this.form.sendSuccessMsg = this.form.sendSuccessMsg ? 1 : 0;
          //	处理请求参数
          const _obj = JSON.parse(JSON.stringify(this.form));
          _obj.sendSuccessMsg = this.form.sendSuccessMsg ? 1 : 0;
          const _params = await paramsDataDeal(_obj);
          delete _params.webapiUseridArr;
          if (_params.id) {
            updateWebapiById(_params).then((res) => {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.getPageList();
              this.dialogFormVisible = false;
            });
          } else {
            createWebapi(_params).then((res) => {
              this.$message({
                message: "新增成功",
                type: "success",
              });
              this.getPageList();
              this.dialogFormVisible = false;
            });
          }
        } else {
          return false;
        }
      });
    },

    // 取消
    resetForm(formName) {
      this.dialogFormVisible = false;
      this.isDetails = false;
      // this.form = {
      //   id: "",
      //   webapiClass: "",
      //   webapiName: "",
      //   webapiContent: "",
      //   webapiType: null,
      //   webapiEndtime: null,
      //   webapiUserid: null,
      //   webapiConfig: null,
      //   brandId: null,
      //   brandName: "",
      //   projectId: null,
      //   projectName: "",
      //   testingInterval: 1,
      //   sendSuccessMsg: true,
      //   webapiMethod: "",
      //   webapiDomain: "",
      //   webapiPath: "",
      //   webapiCheck: "",
      //   webapiData: null,
      //   webapiUseridArr: [],
      // }
    },
    // 新增通知任务
    handleAdd() {
      checkUserToken().then((res) => {
        if (res.data) {
          this.tagWebapi = null;
          this.title = "新增任务告警";
          this.isDetails = false;
          this.$delete(this.form, "id");
          this.form.webapiUseridArr = [this.currTagUserId];
          this.form.webapiName = "";
          this.form.webapiContent = null;
          this.form.webapiType = "";
          this.form.webapiConfig = "";
          this.form.webapiEndtime = null;
          this.form.webapiUserid = null;
          this.form.brandId = null;
          this.form.brandName = null;
          this.form.projectId = null;
          this.form.projectName = null;
          this.form.testingInterval = 1;
          this.form.sendSuccessMsg = true;
          this.form.webapiMethod = null;
          this.form.webapiDomain = null;
          this.form.webapiPath = null;
          this.form.webapiCheck = null;
          this.form.webapiClass = null;
          this.form.webapiData = this.webapiDataObj;
          this.$nextTick(() => {
            this.$refs["form"].resetFields();
          });
          this.dialogFormVisible = true;
        }
      });
    },
    //  详情
    handleDetails(row) {
      this.title = "查看任务告警";
      this.dialogFormVisible = true;
      this.isDetails = true;
      this.$nextTick(() => {
        if (this.$refs['form']) {
          this.$refs['form'].clearValidate();
        }
        this.tagWebapi = row;
        this.form.id = row.id;
        this.form.webapiName = row.webapi_name;
        this.form.webapiContent = row.webapi_content;
        this.form.webapiType = row.webapi_type;
        this.form.webapiConfig = JSON.parse(row.webapi_config);
        this.form.webapiEndtime = new Date(row.webapi_endtime);
        this.form.webapiUserid = null;
        this.form.brandId = row.brand_id;
        this.form.brandName = row.brand_name;
        this.form.projectId = row.project_id;
        this.form.projectName = row.project_name;
        this.form.testingInterval = row.testing_interval;
        this.form.sendSuccessMsg = row.send_success_msg ? true : false;
        this.form.webapiMethod = row.webapi_method;
        this.form.webapiDomain = row.webapi_domain;
        this.form.webapiPath = row.webapi_path;
        this.form.webapiClass = row.webapi_class || "";
        this.form.webapiCheck = row.webapi_check;
        this.form.webapiData = JSON.parse(row.webapi_data);
        this.form.webapiUseridArr = [];
        if (row.webapi_userid) {
          const _ids = row.webapi_userid.split(",");
          _ids.forEach((el) => {
            this.userLists.forEach((item) => {
              if (el == item.userid) {
                this.form.webapiUseridArr.push(item.unionid);
              }
            });
          });
        }
      });
    },
    // 修改 任务状态
    async handleChangeDetails(row) {
      let _msg = "";
      let _webapiStatus = "";
      if (row.webapi_status == "NOT_START" || row.webapi_status == "END") {
        _webapiStatus = "START";
        _msg = "启动";
        //  判断当前任务是否进行手动测试
        const logsCount = await testingLogsById({ id: row.id });
        if (logsCount.success && logsCount.data == 0) {
          return this.$message({
            type: "warning",
            message: "请先进行一次手动测试，再执行任务启动操作！",
          })
        };
        //  验证当前任务是否手动测试成功
        if (row.testing_status != "1") {
          return this.$message({
            type: "warning",
            message: row.testing_status == "0" ? "请检查：网站&API信息配置信息是否正确" : "请检查：基础信息-通知配置信息是否正确",
          });
        }
      } else if (row.webapi_status == "START") {
        _webapiStatus = "END";
        _msg = "结束";
      }
      if (_msg && _webapiStatus) {
        //  更新webapi状态
        const res = await updateStatusByid({ id: row.id, webapiStatus: _webapiStatus });
        this.getPageList();
        if (res && res.success) {
          this.$message({
            type: "success",
            message: "任务" + _msg + "成功",
          })
        } else {
          this.$message({
            type: "error",
            message: "任务" + _msg + "失败",
          })
        }
      } else {
        this.$message({
          type: "error",
          message: "未知任务状态",
        })
      }
    },
    // 修改
    handleModify(row) {
      if (row.webapi_status === "START")
        return this.$message({
          type: "info",
          message: "任务状态为“进行中”，请结束任务再执行修改操作",
        });
      this.title = "修改任务告警";
      this.dialogFormVisible = true;
      this.isDetails = false;
      this.$nextTick(() => {
        if (this.$refs['form']) {
          this.$refs['form'].clearValidate();
        }
        this.tagWebapi = row;
        this.form.id = row.id;
        this.form.webapiName = row.webapi_name;
        this.form.webapiContent = row.webapi_content;
        this.form.webapiType = row.webapi_type;
        this.form.webapiConfig = JSON.parse(row.webapi_config);
        this.form.webapiEndtime = new Date(row.webapi_endtime);
        this.form.webapiUserid = null;
        this.form.brandId = row.brand_id;
        this.form.brandName = row.brand_name;
        this.form.projectId = row.project_id;
        this.form.projectName = row.project_name;
        this.form.testingInterval = row.testing_interval;
        this.form.sendSuccessMsg = row.send_success_msg ? true : false;
        this.form.webapiMethod = row.webapi_method;
        this.form.webapiDomain = row.webapi_domain;
        this.form.webapiPath = row.webapi_path;
        this.form.webapiClass = row.webapi_class || "";
        this.form.webapiCheck = row.webapi_check;
        this.form.webapiData = JSON.parse(row.webapi_data);
        this.form.webapiUseridArr = [];
        if (row.webapi_userid) {
          const _ids = row.webapi_userid.split(",");
          _ids.forEach((el) => {
            this.userLists.forEach((item) => {
              if (el == item.userid) {
                this.form.webapiUseridArr.push(item.unionid);
              }
            });
          });
        }
      });
    },
    /**
     * 查看日志
     * @param {*} row 
     */
    async handleLogs(row){
      this.webapiLogsVisible = true;
      const res = await getLogsById({ id: row.id });
      this.webapiLogsData = res && res.data ? res.data : [];
    },
    // 删除
    handleDelete(row) {
      if (row.webapi_status === "START")
        return this.$message({
          type: "info",
          message: "任务状态为“进行中”，请结束任务再执行删除操作",
        });
      this.$confirm("此操作将删除该任务通知, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delWebapiById({ id: row.id }).then((res) => {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getPageList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 输入字数限制
    changeValue(attr, byte) {
      let value = this.form[attr]; //校验的字段
      // 中文、中文标点、全角字符按1长度，英文、英文符号、数字按0.5长度计算
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/;
      let maxLimitStr = byte; //25个汉字
      let pass = true;
      let substringStr = "";
      let length = 0;
      let strArr = value.split("");
      strArr.map((str) => {
        if (pass) {
          if (cnReg.test(str)) {
            //中文
            length++;
          } else {
            //英文
            length += 0.5;
          }
          //大于最大限制的时候
          if (length > maxLimitStr) {
            pass = false;
            //将校验的字符截取返回
            this.form[attr] = substringStr;
          } else {
            substringStr += str;
          }
        }
      });
      return pass;
    },
  },
};